package FinalProject;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;

public class RoomManager extends Vector<Object> { // class which send message

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	RoomManager() {
	}

	void add(Omok_Thread ot) { // add thread.

		super.add(ot);

	}

	void remove(Omok_Thread ot) { // remove thread.

		super.remove(ot);

	}

	Omok_Thread getOT(int i) { // return thread i .

		return (Omok_Thread) elementAt(i);

	}

	Socket getSocket(int i) { // return socket i.

		return getOT(i).getSocket();

	}

	// send message to connected i thread.
	void sendTo(int i, String msg) {

		try {

			PrintWriter pw = new PrintWriter(
					getSocket(i).getOutputStream(), true);

			pw.println(msg);

		} catch (Exception e) {
		}

	}

	int getRoomNumber(int i) { // return room number of thread i.

		return getOT(i).getRoomNumber();

	}

	synchronized boolean isFull(int roomNum) { // check the room is full.

		if (roomNum == 0)
			return false; // waiting room has no limit.

		// the other room has limit 2 people.
		int count = 0;

		for (int i = 0; i < size(); i++) {
			if (roomNum == getRoomNumber(i))
				count++;

			if (count >= 2)
				return true;
		}
		return false;

	}

	// send the message to room Number.
	void sendToRoom(int roomNum, String msg) {

		for (int i = 0; i < size(); i++) {
			if (roomNum == getRoomNumber(i))

				sendTo(i, msg);
		}

	}

	// send the message to user who is in same room as ot.
	void sendToOthers(Omok_Thread ot, String msg) {

		for (int i = 0; i < size(); i++) {
			if (getRoomNumber(i) == ot.getRoomNumber() && getOT(i) != ot)

				sendTo(i, msg);
		}
	}

	// return check result that is the ready of start game
	// if all of two user is ready, return true
	synchronized boolean isReady(int roomNum) {

		int count = 0;

		for (int i = 0; i < size(); i++) {
			if (roomNum == getRoomNumber(i) && getOT(i).isReady())

				count++;

			if (count == 2)
				return true;
		}
		return false;

	}

	// return users name in room roomNum
	String getNamesInRoom(int roomNum) {

		StringBuffer sb = new StringBuffer("[PLAYERS]");

		for (int i = 0; i < size(); i++) {
			if (roomNum == getRoomNumber(i))

				sb.append(getOT(i).getUserName() + "\t");
		}
		return sb.toString();

	}
}

